<?php
// 禁用错误输出，避免破坏JSON响应
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require_once '../config.php';
require_once 'BaseAPI.php';

handleCORS();

class BookmarksAPI extends BaseAPI {
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        
        // 获取请求数据
        $requestData = getRequestData();
        
        // 优先从GET/POST参数获取action，兼容虚拟主机
        $action = $_GET['action'] ?? $_POST['action'] ?? $requestData['action'] ?? '';
        $id = $_GET['id'] ?? $_POST['id'] ?? $requestData['id'] ?? '';
        
        // 如果没有action参数，尝试从URL路径解析
        if (empty($action)) {
            $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $pathParts = explode('/', trim($path, '/'));
            $action = end($pathParts);
            
            // 移除.php后缀
            $action = str_replace('.php', '', $action);
            
            // 检查是否是数字ID
            if (is_numeric($action)) {
                $id = $action;
                $action = 'bookmark'; // 默认操作
            }
        }
        
        try {
            switch ($method) {
                case 'GET':
                    if ($id || is_numeric($action)) {
                        $bookmarkId = $id ?: $action;
                        $this->getBookmark($bookmarkId);
                    } else {
                        $this->getBookmarks();
                    }
                    break;
                case 'POST':
                    if ($action === 'update' || $action === 'move' || $action === 'delete') {
                        // 支持POST方式的更新、移动和删除（虚拟主机兼容）
                        if ($action === 'update') {
                            if ($id) {
                                $this->updateBookmark($id);
                            } else {
                                sendErrorResponse('缺少收藏ID', 400);
                            }
                        } elseif ($action === 'move') {
                            if ($id) {
                                $this->moveBookmark($id);
                            } else {
                                sendErrorResponse('缺少收藏ID', 400);
                            }
                        } elseif ($action === 'delete') {
                            if ($id) {
                                $this->deleteBookmark($id);
                            } else {
                                sendErrorResponse('缺少收藏ID', 400);
                            }
                        }
                    } else {
                        $this->createBookmark();
                    }
                    break;
                case 'PUT':
                    if ($id || is_numeric($action)) {
                        $bookmarkId = $id ?: $action;
                        $this->updateBookmark($bookmarkId);
                    } else {
                        sendErrorResponse('缺少收藏ID', 400);
                    }
                    break;
                case 'DELETE':
                    if ($action === 'delete' || $id || is_numeric($action)) {
                        $bookmarkId = $id ?: $action;
                        $this->deleteBookmark($bookmarkId);
                    } else {
                        sendErrorResponse('缺少收藏ID', 400);
                    }
                    break;
                default:
                    sendErrorResponse('不支持的请求方法', 405);
            }
        } catch (Exception $e) {
            logActivity("收藏API错误: " . $e->getMessage(), 'ERROR');
            sendErrorResponse('服务器内部错误', 500);
        }
    }
    
    private function getBookmarks() {
        $user = $this->requireAuth();
        
        // 获取查询参数
        $page = max(1, intval($_GET['page'] ?? 1));
        $limit = min(100, max(10, intval($_GET['limit'] ?? 20)));
        $search = $_GET['search'] ?? '';
        $category = $_GET['category'] ?? '';
        $offset = ($page - 1) * $limit;
        
        // 构建查询条件
        $where = ['b.user_id = ?'];
        $params = [$user['id']];
        
        if ($search) {
            $where[] = '(b.name LIKE ? OR b.url LIKE ? OR b.description LIKE ?)';
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }
        
        if ($category && $category !== 'all') {
            $where[] = 'b.category_id = ?';
            $params[] = $category;
        }
        
        $whereClause = implode(' AND ', $where);
        
        // 获取总数 - 需要使用JOIN查询来统计
        $countSql = "
            SELECT COUNT(*) as total 
            FROM bookmarks b 
            LEFT JOIN categories c ON b.category_id = c.id
            WHERE $whereClause
        ";
        $stmt = $this->db->prepare($countSql);
        $stmt->execute($params);
        $total = $stmt->fetch()['total'];
        
        // 获取收藏列表
        $sql = "
            SELECT b.id, b.name, b.url, b.favicon, b.description, b.is_private, 
                   b.sort_order, b.created_at, b.updated_at,
                   c.id as category_id, c.name as category_name, c.color as category_color, c.icon as category_icon
            FROM bookmarks b 
            LEFT JOIN categories c ON b.category_id = c.id
            WHERE $whereClause 
            ORDER BY b.created_at DESC 
            LIMIT ? OFFSET ?
        ";
        $params[] = $limit;
        $params[] = $offset;
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $bookmarks = $stmt->fetchAll();
        
        // 获取分组统计
        $categorySql = "
            SELECT c.id, c.name, c.color, c.icon, COUNT(b.id) as count 
            FROM categories c
            LEFT JOIN bookmarks b ON c.id = b.category_id AND b.user_id = c.user_id
            WHERE c.user_id = ? 
            GROUP BY c.id, c.name, c.color, c.icon
            ORDER BY c.sort_order ASC
        ";
        $stmt = $this->db->prepare($categorySql);
        $stmt->execute([$user['id']]);
        $categories = $stmt->fetchAll();
        
        sendSuccessResponse([
            'bookmarks' => $bookmarks,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'pages' => ceil($total / $limit)
            ],
            'categories' => $categories
        ]);
    }
    
    private function getBookmark($id) {
        $user = $this->requireAuth();
        
        $stmt = $this->db->prepare("
            SELECT b.id, b.name, b.url, b.favicon, b.description, b.is_private, 
                   b.sort_order, b.created_at, b.updated_at,
                   c.id as category_id, c.name as category_name, c.color as category_color, c.icon as category_icon
            FROM bookmarks b 
            LEFT JOIN categories c ON b.category_id = c.id
            WHERE b.id = ? AND b.user_id = ?
        ");
        $stmt->execute([$id, $user['id']]);
        $bookmark = $stmt->fetch();
        
        if (!$bookmark) {
            sendErrorResponse('收藏不存在', 404);
        }
        
        sendSuccessResponse(['bookmark' => $bookmark]);
    }
    
    private function createBookmark() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        // 验证输入
        $rules = [
            'name' => [
                'required' => true,
                'max_length' => 255,
                'message' => '收藏名称不能为空且不超过255个字符'
            ],
            'url' => [
                'required' => true,
                'url' => true,
                'message' => '请输入有效的网址'
            ],
            'description' => [
                'max_length' => 1000,
                'message' => '描述不能超过1000个字符'
            ],
            'category' => [
                'max_length' => 100,
                'message' => '分类名称不能超过100个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $name = $data['name'];
        $url = $data['url'];
        $description = $data['description'] ?? '';
        $categoryId = $data['category_id'] ?? null;
        $isPrivate = isset($data['is_private']) ? (bool)$data['is_private'] : false;
        
        // 确保URL包含协议
        if (!preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }
        
        // 验证分组是否存在（如果提供了分组ID）
        if ($categoryId) {
            $stmt = $this->db->prepare("SELECT id FROM categories WHERE id = ? AND user_id = ?");
            $stmt->execute([$categoryId, $user['id']]);
            if (!$stmt->fetch()) {
                sendErrorResponse('指定的分组不存在');
            }
        }
        
        // 生成favicon URL
        $favicon = $this->generateFaviconUrl($url);
        
        // 检查是否已存在相同的URL
        $stmt = $this->db->prepare("SELECT id FROM bookmarks WHERE user_id = ? AND url = ?");
        $stmt->execute([$user['id'], $url]);
        if ($stmt->fetch()) {
            sendErrorResponse('该网址已经存在于收藏中');
        }
        
        // 获取下一个排序序号
        $stmt = $this->db->prepare("SELECT COALESCE(MAX(sort_order), -1) + 1 as next_order FROM bookmarks WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        $sortOrder = $stmt->fetch()['next_order'];
        
        // 创建收藏
        $stmt = $this->db->prepare("
            INSERT INTO bookmarks (user_id, category_id, name, url, favicon, description, is_private, sort_order) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        if ($stmt->execute([$user['id'], $categoryId, $name, $url, $favicon, $description, $isPrivate, $sortOrder])) {
            $bookmarkId = $this->db->lastInsertId();
            
            // 获取创建的收藏
            $stmt = $this->db->prepare("
                SELECT b.id, b.name, b.url, b.favicon, b.description, b.is_private, 
                       b.sort_order, b.created_at, b.updated_at,
                       c.id as category_id, c.name as category_name, c.color as category_color, c.icon as category_icon
                FROM bookmarks b 
                LEFT JOIN categories c ON b.category_id = c.id
                WHERE b.id = ?
            ");
            $stmt->execute([$bookmarkId]);
            $bookmark = $stmt->fetch();
            
            logActivity("用户创建收藏: {$user['username']} - $name");
            sendSuccessResponse(['bookmark' => $bookmark], '收藏添加成功');
        } else {
            sendErrorResponse('收藏添加失败');
        }
    }
    
    private function updateBookmark($id) {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        // 验证收藏是否存在且属于当前用户
        $stmt = $this->db->prepare("SELECT * FROM bookmarks WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user['id']]);
        $bookmark = $stmt->fetch();
        
        if (!$bookmark) {
            sendErrorResponse('收藏不存在', 404);
        }
        
        // 验证输入
        $rules = [
            'name' => [
                'max_length' => 255,
                'message' => '收藏名称不能超过255个字符'
            ],
            'url' => [
                'url' => true,
                'message' => '请输入有效的网址'
            ],
            'description' => [
                'max_length' => 1000,
                'message' => '描述不能超过1000个字符'
            ],
            'category' => [
                'max_length' => 100,
                'message' => '分类名称不能超过100个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $updates = [];
        $params = [];
        
        if (isset($data['name']) && $data['name'] !== $bookmark['name']) {
            $updates[] = 'name = ?';
            $params[] = $data['name'];
        }
        
        if (isset($data['url']) && $data['url'] !== $bookmark['url']) {
            $url = $data['url'];
            if (!preg_match('/^https?:\/\//', $url)) {
                $url = 'https://' . $url;
            }
            
            // 检查新URL是否已存在
            $stmt = $this->db->prepare("SELECT id FROM bookmarks WHERE user_id = ? AND url = ? AND id != ?");
            $stmt->execute([$user['id'], $url, $id]);
            if ($stmt->fetch()) {
                sendErrorResponse('该网址已经存在于收藏中');
            }
            
            $updates[] = 'url = ?';
            $params[] = $url;
            
            // 更新favicon
            $updates[] = 'favicon = ?';
            $params[] = $this->generateFaviconUrl($url);
        }
        
        if (isset($data['description'])) {
            $updates[] = 'description = ?';
            $params[] = $data['description'];
        }
        
        if (isset($data['category_id'])) {
            // 验证分组是否存在（如果不为null）
            if ($data['category_id'] !== null) {
                $stmt = $this->db->prepare("SELECT id FROM categories WHERE id = ? AND user_id = ?");
                $stmt->execute([$data['category_id'], $user['id']]);
                if (!$stmt->fetch()) {
                    sendErrorResponse('指定的分组不存在');
                }
            }
            $updates[] = 'category_id = ?';
            $params[] = $data['category_id'];
        }
        
        if (isset($data['is_private'])) {
            $updates[] = 'is_private = ?';
            $params[] = (bool)$data['is_private'];
        }
        
        if (isset($data['sort_order']) && is_numeric($data['sort_order'])) {
            $updates[] = 'sort_order = ?';
            $params[] = intval($data['sort_order']);
        }
        
        if (empty($updates)) {
            sendErrorResponse('没有需要更新的信息');
        }
        
        $params[] = $id;
        $sql = "UPDATE bookmarks SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        
        if ($stmt->execute($params)) {
            // 获取更新后的收藏
            $stmt = $this->db->prepare("
                SELECT b.id, b.name, b.url, b.favicon, b.description, b.is_private, 
                       b.sort_order, b.created_at, b.updated_at,
                       c.id as category_id, c.name as category_name, c.color as category_color, c.icon as category_icon
                FROM bookmarks b 
                LEFT JOIN categories c ON b.category_id = c.id
                WHERE b.id = ?
            ");
            $stmt->execute([$id]);
            $updatedBookmark = $stmt->fetch();
            
            logActivity("用户更新收藏: {$user['username']} - {$updatedBookmark['name']}");
            sendSuccessResponse(['bookmark' => $updatedBookmark], '收藏更新成功');
        } else {
            sendErrorResponse('收藏更新失败');
        }
    }
    
    
    private function generateFaviconUrl($url) {
        try {
            $parsedUrl = parse_url($url);
            $domain = $parsedUrl['host'] ?? '';
            if ($domain) {
                return "https://www.google.com/s2/favicons?domain={$domain}&sz=32";
            }
        } catch (Exception $e) {
            // 忽略错误
        }
        
        return null;
    }
    
    // getAuthToken() 和 requireAuth() 已在 BaseAPI 中实现

    // 移动收藏到分组
    private function moveBookmark($id) {
        $user = $this->requireAuth();

        // 获取POST数据
        $data = getRequestData();

        $categoryId = $data['category_id'] ?? null;

        // 验证收藏是否存在且属于当前用户
        $stmt = $this->db->prepare("SELECT id FROM bookmarks WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user['id']]);
        if (!$stmt->fetch()) {
            sendErrorResponse('收藏不存在或无权限访问');
        }

        // 如果指定了分组，验证分组是否存在且属于当前用户
        if ($categoryId !== null) {
            $stmt = $this->db->prepare("SELECT id FROM categories WHERE id = ? AND user_id = ?");
            $stmt->execute([$categoryId, $user['id']]);
            if (!$stmt->fetch()) {
                sendErrorResponse('指定的分组不存在');
            }
        }

        // 更新收藏的分组
        try {
            $stmt = $this->db->prepare("
                UPDATE bookmarks 
                SET category_id = ?, updated_at = NOW() 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->execute([$categoryId, $id, $user['id']]);

            if ($stmt->rowCount() === 0) {
                sendErrorResponse('移动失败，收藏可能不存在');
            }

            // 获取更新后的收藏信息（包括分组信息）
            $stmt = $this->db->prepare("
                SELECT b.id, b.name, b.url, b.favicon, b.description, b.is_private, 
                       b.sort_order, b.created_at, b.updated_at,
                       c.id as category_id, c.name as category_name, c.color as category_color, c.icon as category_icon
                FROM bookmarks b 
                LEFT JOIN categories c ON b.category_id = c.id
                WHERE b.id = ? AND b.user_id = ?
            ");
            $stmt->execute([$id, $user['id']]);
            $bookmark = $stmt->fetch();

            sendSuccessResponse('收藏移动成功', ['bookmark' => $bookmark]);
        } catch (Exception $e) {
            error_log("移动收藏失败: " . $e->getMessage());
            sendErrorResponse('移动收藏失败: ' . $e->getMessage());
        }
    }

    // 删除收藏
    private function deleteBookmark($id) {
        $user = $this->requireAuth();
        
        // 确保ID是整数
        $id = intval($id);
        if ($id <= 0) {
            sendErrorResponse('无效的收藏ID', 400);
        }
        
        // 验证收藏是否存在且属于当前用户
        $stmt = $this->db->prepare("SELECT name FROM bookmarks WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user['id']]);
        $bookmark = $stmt->fetch();
        
        if (!$bookmark) {
            sendErrorResponse('收藏不存在或无权限访问', 404);
        }
        
        try {
            // 删除收藏
            $stmt = $this->db->prepare("DELETE FROM bookmarks WHERE id = ? AND user_id = ?");
            $result = $stmt->execute([$id, $user['id']]);
            
            if ($result && $stmt->rowCount() > 0) {
                logActivity("用户删除收藏: {$user['username']} - {$bookmark['name']}");
                sendSuccessResponse(['deleted_id' => $id], '收藏删除成功');
            } else {
                sendErrorResponse('删除失败，收藏可能不存在', 404);
            }
        } catch (Exception $e) {
            error_log("删除收藏失败: " . $e->getMessage());
            sendErrorResponse('删除收藏失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$api = new BookmarksAPI();
$api->handleRequest();
?>
